package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.AdminAction;
import gatperdut.chato.core.interpreter.grammar.comminfo.COIRInfo;
import gatperdut.chato.core.item.ItemController;
import gatperdut.chato.model.Chato.Item.ItemTemplate;

public class COIRAction extends AdminAction {

    public COIRAction( COIRInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        AdminCheckResult acr = checkAdminUser();
        if ( !acr.isAllowed() ) {
            getEntityController().tx( acr.getMessage() );
            return CommandExecutionResult.OK;
        }

        ItemTemplate it = getEntityController().getChatoServer().getItemTemplateHandler().findByHashCode( getInfo().getCode() );

        if ( it == null ) {
            getEntityController().tx( "An item template with that id does not exist." );
            return CommandExecutionResult.OK;
        }

        if ( getInfo().getAmount() != null ) {
            if ( getInfo().getAmount() <= 0 ) {
                getEntityController().tx( "That amount of items does not make sense, does it?" );
                return CommandExecutionResult.OK;
            }
            if ( it.getStack() == null && it.getFood() == null ) {
                getEntityController().tx( "Cannot specify an amount for non-stackable or non-edible items." );
                return CommandExecutionResult.OK;
            }
            if ( it.getStack() != null ) {
                if ( getInfo().getAmount() > it.getStack().getMax() ) {
                    getEntityController().tx( "Maximum stack size for this item is " + it.getStack().getMax() + "." );
                    return CommandExecutionResult.OK;
                }
            }
        }

        ItemController ic = getEntityController().getChatoServer().getItemHandler().genItemController( it );

        if ( getInfo().getAmount() != null ) {
            if ( ic.isStackable() || ic.isEatable() ) {
                ic.getAmountController().setCurrent( getInfo().getAmount() );
            }
        }

        getEntityController().getRoomController().getInventoryController().putInInventory( ic );

        getEntityController().tx( "Item created." );

        return CommandExecutionResult.OK;
    }

    @Override
    public COIRInfo getInfo() {
        return (COIRInfo) super.getInfo();
    }

}
